Online-Academy
Look, Read, Understand, Apply

Package - ii

Package

Example

    Project
        pack1
           Student.java
        pack2
            Main.java
Student.java
package pack1;

public class Student {
    public int id;
    public String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public void display() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
    }
}    

package pack2: This line tells Java that Student belongs to the pack1 package

Import the class into another package

Create Main.java inside pack2:

package pack2;

import pack1.Student;

public class Main {
    public static void main(String[] args) {

        Student s = new Student(101, "Ram");

        s.display();
    }
}    

import pack1.Student: means import the Student class from package pack1. We can create its objec normally.

Student s = new Student(202,"Sitesh");

Complete Flow
pack1
    Student.java
        public class Student
    import pack1.Student
pack2
    Main.java
        Student s - new Student(303,"Sheetal");

Important: public

Wneh accessing a class form another package, the class generally needs to be public:

public class Student

And members we want to access direclty also need to have appropriate access, e.g.:

public int id;

if id were

private int id; or

int id;

We could not access it from pack2.

We can also import everything.

Instead of:

import pack1.Student;

We can write:

import pack1.*;

This (*) imports the accessible classes from pack1.

However, import pack1.* does not import subpackages.

pack1
pack1.subpack

Importing
import pack1.*; //does not import classes from pack1.subpack.

One thing to remember

A package is not an object. We import the class, and then create an object of that class.

        import pack1.Student;   // import class
        Student s = new Student(); //create object
    

So the sequence is:

Create package -> Create class -> Make class accessible (public) -> Import class -> Create object.